package com.alangyun.remind.utils;

import cn.hutool.core.date.DateTime;

import java.util.Calendar;
import java.util.Date;

/**
 * @Author ：helloKitty
 * @Date ：2024/2/8 23:28
 * @Desc ：
 */
public class MyDateUtils {
    /**
     * 判断两个日期间是否超过的年数
     * @param time1
     * @param time2
     * @param numYear
     * @return
     */
    public static Boolean DateCompare(Date time1, Date time2, int numYear) {
        Date time3 = add(time1, Calendar.YEAR, numYear);
        if(time3.getTime() < time2.getTime()){
            // 前者小于后者
            return true;
        }
        return false;
    }

    public static Boolean DateCompare(Date time1, DateTime time2, int numYear) {
        Date time3 = add(time1, Calendar.YEAR, numYear);
        if(time3.getTime() < time2.getTime()){
            // 前者小于后者
            return false;
        }
        return true;
    }

    /**
     * 时间加减
     * @param date
     * @param calendarField ：Calendar.YEAR/ Calendar.MONTH /Calendar.DAY
     * @param amount
     * @return
     */
    public static Date add(final Date date, final int calendarField, final int amount) {
        if (date == null) {
            return null;
        }
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }



    public static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

}
